/**
 * Created by Administrator on 2017/2/27.
 */
const nunjucks = require('nunjucks');//可以有效防止恶意脚本的输出
/**
 * 创建模板管理器
 * @param path
 * @param opts
 */
const createEnv =(path,opts)=>{
    var autoescape = opts.autoescape && true,   //控制输出是否被转义
        noCache = opts.noCache || false,    //不使用缓存，每次都重新编译
        wacth = opts.watch || false,    //当模板变化时重新加载
        throwOnUndefined = opts.throwOnUndefined || false, //当输出为null或undefined抛出异常
        env = new nunjucks.Environment(
            new nunjucks.FileSystemLoader('views',{
                noCache:noCache,
                wacth:wacth,
            }),{
                autoescape:autoescape,
                throwOnUndefined:throwOnUndefined
            });
    /**
     * 添加自定义过滤器
     */
    if (opts.filters){
            for (var f in opts.filters){
                env.addFilter(f,opts.filters[f]);
            }
    }
    return env;
}
/**
 * Nunjucks模板引擎对象
 */
var env = createEnv('views',{
    watch:true,
    filters:{
        hex:(n)=>{
            return '0x'+n.toString(16);
        }
    }
});

/**
 * 渲染模板
 */
var s = env.render('hello.html',{name:'<script>alert("chenjw")</script>'});
//console.log(s);
//渲染子模板
console.log('开始渲染');
var zzz = env.render('base.html',{
    header:'Hello',
    body:'bla bla bla'
})
console.log("子模板："+zzz);